@tool
class_name ContextBehavior_MatchRotation
extends BaseContextBehavior

#region 属性
@export var force:float
## 小于等于这个值认为旋转对齐
@export var alignment_tolerance:float
## 减速角度
@export var deceleration_rotation:float
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init():
	super()
func calc_steering(behaviors_owner:Node,agent:SteeringBehaviorAgent,delta:float):
	super(behaviors_owner,agent,delta)
	calc_angular_interest()
#endregion
#region 公共方法
func get_target_pos(target:Node2D) -> Vector2:
	return target.global_position
func get_match_rotation(target_rot:float) -> float:
	var rotation = wrapf(target_rot - agent.get_rot(),-PI,PI)
	var rotation_abs = absf(rotation)
	if rotation_abs <= deg_to_rad(alignment_tolerance):
		return 0
	var desired_rotation = agent.angular_speed_max
	if rotation_abs <= deg_to_rad(deceleration_rotation):
		desired_rotation *= rotation_abs / deg_to_rad(deceleration_rotation)
	desired_rotation *= rotation / rotation_abs
	return desired_rotation
func calc_angular_interest():
	var detect_component:DetectComponent = agent.entity.get_component(DetectComponent)
	if not detect_component:
		return
	var detector_target:Detector_Target = detect_component.get_detector(GameEnum.DetectorType.Target)
	if not detector_target:
		return
	var targets = detector_target.get_targets(agent.get_pos(),0,Callable(),1)
	if targets.size() < 1:
		return
	var closed_target = targets[0]
	var angular_interest:float = get_match_rotation(closed_target.rotation) * sensitive
	agent.add_angular_interest(angular_interest * force)
#endregion
#region 私有方法
#endregion
#region 生命周期函数
func _init() -> void:
	if Engine.is_editor_hint():
		resource_local_to_scene = true
	behavior_type = GameEnum.ContextBehaviorType.MathRotation
func draw() -> void:
	super.draw()
#endregion
